package com.coder306.shiro;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coder306.util.WebResult;

public class ApiAuthenticatingFilter extends AuthenticatingFilter {
	
	private static final Logger log = LoggerFactory.getLogger(ApiAuthenticatingFilter.class);
	
	public static final String DEFAULT_USERNAME_PARAM = "username";
    public static final String DEFAULT_PASSWORD_PARAM = "password";

	@Override
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
		String username = request.getParameter(DEFAULT_USERNAME_PARAM);
		String password = request.getParameter(DEFAULT_PASSWORD_PARAM);
		return super.createToken(username, password, request, response);
	}
	
	/**
	 * 是否是POST请求
	 * @param request
	 * @param response
	 * @return
	 */
	protected boolean isLoginSubmission(ServletRequest request, ServletResponse response) {
        return (request instanceof HttpServletRequest) && WebUtils.toHttp(request).getMethod().equalsIgnoreCase(POST_METHOD);
    }
	
	/**
	 * 执行登陆
	 */
	@Override
	protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
		AuthenticationToken token = createToken(request, response);
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                    "must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        }
        try {
            Subject subject = getSubject(request, response);
            subject.login(token);
            return onLoginSuccess(token, subject, request, response);
        } catch (AuthenticationException e) {
            return onLoginFailure(token, e, request, response);
        }
	}
	
	/**
	 * 登陆成功
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
			ServletResponse response) throws Exception {
		return super.onLoginSuccess(token, subject, request, response);
	}
	
	@Override
	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		//登陆失败
        try {
			returnJson((HttpServletRequest)request,(HttpServletResponse)response,WebResult.getErrorResult(WebResult.Code.LOGIN_ERROR));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return super.onLoginFailure(token, e, request, response);
	}
	
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		if (isLoginRequest(request, response)) {
			/*
			 * 访问登陆接口 
			 */
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                //需要登录权限
                returnJson((HttpServletRequest)request,(HttpServletResponse)response,WebResult.getErrorResult(WebResult.Code.REQUIRE_ERROR));
                return false;
            }
        } else {
        	/*
        	 * 访问非登陆接口
        	 */
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                        "Authentication url [" + getLoginUrl() + "]");
            }
            
            //需要登录权限
            returnJson((HttpServletRequest)request,(HttpServletResponse)response,WebResult.getErrorResult(WebResult.Code.REQUIRE_ERROR));
            return false;
        }
	}
	
	/**
	 * 返回JSON数据
	 * @param response
	 * @param json
	 * @throws Exception
	 */
	private void returnJson(HttpServletRequest request,HttpServletResponse response, WebResult<?> result) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result.toString());
        } catch (IOException e) {
        	log.error("response error",e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
